package org.atlantis.grosbeak.cable;

import javax.servlet.http.HttpServletRequest;

import org.atlantis.grosbeak.cable.meta.RequestAware;
import org.atlantis.grosbeak.castor.Castors;

class DefaultRequestAware implements RequestAware {

	private HttpServletRequest request;
	private String[] params;

	public DefaultRequestAware(HttpServletRequest request, String[] params) {
		this.request = request;
		this.params = params;
	}

	public String getPostParam(String key) {
		if ("POST".equalsIgnoreCase(request.getMethod())) {
			return request.getParameter(key);
		}
		return null;
	}

	public <T> T getPostParam(Class<T> type, String key) {
		if ("POST".equalsIgnoreCase(request.getMethod())) {
			String value = request.getParameter(key);
			T result = Castors.me().castTo(value, type);
			return result;
		}
		return null;
	}

	public HttpServletRequest getSelf() {
		return request;
	}

	public void setAttr(String key, Object value) {
		request.setAttribute(key, value);
	}

	public String getGetParam(ParamIndex index) {
		if ("GET".equalsIgnoreCase(request.getMethod())) {
			int i = index.ordinal();
			if (i >= params.length)
				return null;
			return params[i];
		}
		return null;
	}

	public <T> T getGetParam(Class<T> type, ParamIndex index) {
		String result = getGetParam(index);
		if (result != null)
			return Castors.me().castTo(result, type);
		return null;
	}
}
